import { useState, useEffect } from 'react';
import utils from '@/utils/utils';
import './index.less';
import { Link, useNavigate } from 'react-router-dom';
import Item from './item';
import aipeilianzi from '@/assets/AiImgs/aipeilianzi.png';
import { IconCaretRight } from '@arco-design/web-react/icon';
import { getAiTrainList } from '@/api/train';

export default function TrainList() {
  const navigate = useNavigate();
  const [list, setList] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    setLoading(true);
    setError(false);
    
    getAiTrainList()
      .then((res: any) => {
        // 安全获取数据并过滤无效分类
        const categories = res?.data?.list || [];
        const validCategories = categories.filter(
          (category: any) => 
            category?.catagory_name && 
            category?.training_list?.length
        );
        
        setList(validCategories);
        setLoading(false);
      })
      .catch(() => {
        setError(true);
        setLoading(false);
      });
  }, []);

  // 完全保持原有布局结构
  return (
    <div className='text-[#222222] h-screen overflow-y-auto'>
      {/* 顶部区域 - 完全保持原设计 */}
      <div className="px-6 pt-[98px] pb-5 bg-aipeilian">
        <img className='w-[125px]' src={aipeilianzi} alt="AI陪练" />
        <Link to="/practiceRecord">
          <button className='border mt-1.5 text-xs border-[0.5px] px-3 py-1 border-[rgba(0, 0, 0, 0.2)] rounded-full xunlian border-gray-500'>
            训练记录
            <IconCaretRight style={{color:'#DB0007'}}/>
          </button>
        </Link>
        <Link to="/SettingPage">
          <button className='border mt-1.5 ml-2.5 text-xs border-[0.5px] px-3 py-1 border-[rgba(0, 0, 0, 0.2)] rounded-full xunlian border-gray-500'>
            设置
          </button>
        </Link>
      </div>

      {/* 内容区域 - 保持原有样式，增加安全处理 */}
      <div className='px-5 -mt-[50px]'>
        {/* 加载状态 - 不改变原布局，仅添加提示文本 */}
        {/* {loading && (
          <div className="text-center py-8">
            <p className="text-gray-500">加载训练数据中...</p>
          </div>
        )} */}
        
        {/* 错误状态 - 保持原布局风格 */}
        {error && !loading && (
          <div className='bg-white/80 backdrop-blur-md px-5 py-4 rounded-2xl mb-3'>
            <div className="text-center py-4">
              <p className="text-gray-600">数据加载失败，请稍后再试</p>
              <button 
                className="text-red-600 mt-2 text-sm"
                onClick={() => window.location.reload()}
              >
                点击重试
              </button>
            </div>
          </div>
        )}
        
        {/* 空数据状态 - 保持原卡片样式 */}
        {!loading && !error && list.length === 0 && (
          <div className='bg-white/80 backdrop-blur-md px-5 py-4 rounded-2xl mb-3'>
            <div className="text-center py-4">
              <p className="text-gray-600">暂无训练内容</p>
            </div>
          </div>
        )}
        
        {/* 正常数据 - 完全保持原渲染逻辑 */}
        {list.map((m: any, s: number) => {
          // 确保分类有训练项目 - 空项目跳过
          if (!m.training_list || !m.training_list.length) return null;
          
          return (
            <div key={s} className='bg-white/80 backdrop-blur-md px-5 py-4 rounded-2xl mb-3'>
              <div className='text-lg mb-4 flex items-center font-semibold'>
                {/* 安全处理分类图标 */}
                {m.category_icon ? (
                  <img className='mr-3' style={{width: '42px', height: '42px'}} src={m.category_icon} alt={m.catagory_name} />
                ) : (
                  <div className="mr-3 bg-gray-200 border-2 border-dashed rounded-xl" style={{width: '42px', height: '42px'}} />
                )}
                {m.catagory_name || '未命名分类'}
              </div>
              
              {/* 安全处理训练列表 */}
              {m.training_list.map((s: any, index: number) => (
                <Item 
                  key={index} 
                  lastItem={m.training_list.length-1 === index} 
                  id={s.id} 
                  title={s.title} 
                  islatest={s.is_latest}
                />
              ))}
            </div>
          );
        })}
      </div>

      {/* 底部区域 - 完全保持原设计 */}
      <div className='text-center mb-4 '>
        <span className='text-xs text-[#999]'>我是有底线的</span>
      </div>
    </div>
  );
}